<template>
  <div class="addRecovery">
    <div class="cus-title">
      <h4 v-if="state === 'edit'">编辑回收点</h4>
      <h4 v-else>添加回收点</h4>
    </div>
    <div class="cus-hearder">
      回收点信息
    </div>
    <div class="sub-form">
      <el-form ref="firstBindForm" :model="BindForm" label-width="100px" :rules="firstRules">
        <el-form-item label="回收点名称" prop="name">
          <el-input v-model="BindForm.name" max-length="20" placeholder="输入回收点名称" />
        </el-form-item>
        <el-form-item label="联系人" prop="concat">
          <el-input v-model="BindForm.concat" placeholder="输入联系人" />
        </el-form-item>
        <el-form-item
          label="联系方式"
          prop="phone"
        >
          <el-input
            v-model="BindForm.phone"
            maxlength="11"
            minlength="1"
            placeholder="输入联系方式"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="BindForm.remark" placeholder="输入备注内容" />
        </el-form-item>
        <el-form-item label="收货地址：" required style="margin-bottom: 22px">
          <el-col :span="20">
            <el-col :span="24" style="display: flex">
              <el-form-item prop="provinceCode" style="padding-left: 0" class="time">
                <el-select
                  ref="province"
                  v-model="BindForm.provinceCode"
                  @change="handelProvince"
                >
                  <el-option
                    v-for="(item, index) in pca.province"
                    :key="index"
                    :value="item.code"
                    :label="item.name"
                  /> </el-select></el-form-item>
              <el-form-item prop="cityCode" class="time">
                <el-select
                  v-model="BindForm.cityCode"
                  @change="handelCity"
                >
                  <el-option
                    v-for="(item, index) in pca.forCity"
                    :key="index"
                    :value="item.code"
                    :label="item.name"
                  /> </el-select></el-form-item>
              <el-form-item prop="areaCode" class="time">
                <el-select
                  v-model="BindForm.areaCode"
                  @change="handelArea"
                >
                  <el-option
                    v-for="(item, index) in pca.forArea"
                    :key="index"
                    :value="item.code"
                    :label="item.name"
                  /> </el-select></el-form-item>
            </el-col>
          </el-col>
        </el-form-item>
        <el-form-item prop="detailAddress" style="margin-bottom: 22px">
          <el-col :span="20">
            <el-amap-search-box
              ref="searchBox"
              v-model="BindForm.detailAddress"
              style="border-radius: 5px; border: 1px solid #F3F3F3;height: 36px;"
              :search-option="searchOption"
              :on-search-result="onSearchResult"
            />
          </el-col>
        </el-form-item>
        <el-form-item style="margin-bottom: 22px">
          <el-col :span="20">
            <el-amap
              ref="map"
              vid="amapDemo"
              :amap-manager="amapManager"
              :center="center"
              :zoom="zoom"
              :plugin="plugin"
              :events="events"
              class="amap-demo"
              style="height:500px;"
            >
              <el-amap-marker :position="center" />
            </el-amap>
          </el-col>
        </el-form-item>
      </el-form>
    </div>
    <div class="cus-hearder">
      其他设置
    </div>
    <div class="sub-form">
      <el-form ref="BindForm" :model="BindForm" label-width="100px" :rules="rules">
        <el-form-item label="上门回收" prop="doorRecovery">
          <el-radio-group v-model="BindForm.doorRecovery">
            <el-radio label="1">支持</el-radio>
            <el-radio label="0">不支持</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-alert
            title="不支持则不能上门回收，只能用户送回或者寄回。如果支持上门回收，则按照运费规则收取上门费用。"
            type="info"
            :closable="false"
          />
        </el-form-item>
        <el-form-item v-if="BindForm.doorRecovery=='1'" prop="supportDistance" class="supportDistance">
          <span style="margin-right: 100px;">支持上门距离</span>
          <span>方圆</span>
          <el-input
            v-model.trim="BindForm.supportDistance"
            placeholder="请输入公里数"
            @keyup.native="changeSupportDistance"
          />
          <span>公里</span>
        </el-form-item>
        <el-form-item>
          <el-button
            v-if="state == 'add' || state == 'edit'"
            type="primary"
            class="submitButton"
            @click="handelSubmit"
          >提交</el-button>
          <el-button type="info" @click="reback">
            返回上一页
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { Loading } from 'element-ui'
import { getCityList } from '@/api/auth'
import VueAMap from 'vue-amap'
import { addRecovery, updateRecovery } from '@/api/customAPI/shop/recoveryManage'
const amapManager = new VueAMap.AMapManager()
export default {
  name: 'AddRecovery',
  components: {

  },
  data() {
    const self = this
    return {
      visible: false,
      state: '',
      id: null,
      pca: {
        // 省区
        province: [],
        // 需要循环遍历的城区和市区
        city: [],
        area: [],
        // 最后拿到的 城区和市区 select 列表
        forCity: [],
        forArea: []
      },
      BindForm: {
        shopId: localStorage.getItem('shopId'),
        name: null,
        concat: null,
        phone: null,
        remark: null,
        provinceId: '',
        provinceName: '',
        cityId: '',
        cityName: '',
        areaId: '',
        areaName: '',
        provinceCode: '',
        cityCode: '',
        areaCode: '',
        detailAddress: '',
        doorRecovery: null,
        supportDistance: null,
        lng: null,
        lat: null
      },
      firstRules: {
        name: [
          { required: true, message: '请输入回收点名称', trigger: 'blur' },
          { max: 20, message: '输入的字符超过20个', trigger: 'change' }
        ],
        concat: [
          { required: true, message: '请输入联系人', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系方式', trigger: 'blur' }
        ],
        provinceCode: [
          { required: true, message: '请选择省份', trigger: 'change' }
        ],
        cityCode: [{ required: true, message: '请选择市', trigger: 'change' }],
        areaCode: [{ required: true, message: '请选择地区', trigger: 'change' }],
        detailAddress: [
          { required: true, message: '请输入具体地址', trigger: 'blur' }
        ]
      },
      rules: {
        doorRecovery: [
          { required: true, message: '请选择上门回收方式', trigger: ['blur', 'change'] }
        ],
        supportDistance: [
          { required: true, message: '请输入公里数', trigger: 'blur' }
        ]
      },
      /** 高德地图*/
      amapManager,
      zoom: 18,
      markers: [],
      searchOption: {
        city: '杭州',
        citylimit: false
      },
      center: [120.19, 30.26],
      events: {
        init: (o) => {
          o.getCity((result) => {
            console.log(result)
          })
        },
        moveend: () => {},
        zoomchange: () => {},
        click: (e) => {
          let geocoder
          self.amapManager.plugin(['AMap.Geocoder'], function() {
            geocoder = self.amapManager.Geocoder({
              radius: 1000,
              extensions: 'all'
            })
          })
          this.center = [e.lnglat.lng, e.lnglat.lat]
          geocoder.getAddress(this.center, function(status, result) { // 根据坐标获取位置
            if (status === 'complete' && result.info === 'OK') {
              self.BindForm.detailAddress = result.regeocode.formattedAddress
              self.$refs.searchBox.keyword = self.BindForm.detailAddress
            }
          })
        }
      },
      plugin: [
        {
          showMarker: true, // 定位成功后在定位到的位置显示点标记，默认：true
          pName: 'Geolocation', // AMap-Geolocation 定位插件
          events: {
            init(o) {
              // getCurrentPosition 获取当前位置的方法
              // 注意 虽然进页面就会调用这个方法，但是data()中center要有默认值，不然会报错
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  const lng = result.position.lng
                  const lat = result.position.lat
                  self.center = [lng, lat]
                  self.loaded = true
                  self.zoom = 18
                  self.$nextTick()
                }
              })
            }
          }
        }
      ]
    }
  },
  created() {
    const params = this.$dd(this.$route.query.p)
    if (!params) {
      this.state = 'add'
    } else {
      this.state = 'edit'
    }
  },
  mounted() {
    const params = this.$dd(this.$route.query.p)
    if (!params) {
      this.state = 'add'
    } else {
      this.state = 'edit'
    }
    this.loadCity()
  },
  methods: {
    /** 初始化信息 */
    inititalInfo() {
      const params = this.$dd(this.$route.query.p)
      if (params) {
        const loadingInstance = Loading.service({ fullscreen: true })
        const info = params.info
        this.id = info.id
        this.BindForm.name = info.name
        this.BindForm.concat = info.contact
        this.BindForm.phone = info.phone
        if (info.remark) {
          this.BindForm.remark = info.remark
        }
        // 省市区处理
        this.BindForm.provinceCode = info.provinceId
          ? info.provinceId
          : ''
        this.BindForm.cityCode = info.cityId
          ? info.cityId
          : ''
        this.BindForm.areaCode = info.areaId
          ? info.areaId
          : ''
        /* console.log(this.pca.province)*/
        this.BindForm.provinceId = this.pca.province.find(inf => {
          return inf.code === this.BindForm.provinceCode
        }).id
        this.BindForm.provinceName = this.pca.province.find(inf => {
          return inf.code === this.BindForm.provinceCode
        }).name
        this.pca.city.forEach(inf => {
          if (inf.pid === this.BindForm.provinceId) {
            this.pca.forCity.push(inf)
          }
        })
        this.BindForm.cityId = this.pca.city.find(inf => {
          return inf.code === this.BindForm.cityCode
        }).id
        this.BindForm.cityName = this.pca.city.find(inf => {
          return inf.code === this.BindForm.cityCode
        }).name
        this.pca.area.forEach(inf => {
          if (inf.pid === this.BindForm.cityId) {
            this.pca.forArea.push(inf)
          }
        })
        this.BindForm.areaId = this.pca.area.find(inf => {
          return inf.code === this.BindForm.areaCode
        }).id
        this.BindForm.areaName = this.pca.area.find(inf => {
          return inf.code === this.BindForm.areaCode
        }).name
        this.BindForm.detailAddress = info.addressDetail

        this.center = [info.lng, info.lat]
        this.BindForm.lng = this.center[0]
        this.BindForm.lat = this.center[1]
        this.BindForm.doorRecovery = info.doorRecovery.toString()
        if (this.BindForm.doorRecovery == '1') {
          this.BindForm.supportDistance = info.supportDistance
        }
        this.$nextTick(() => {
          this.$refs.searchBox.keyword = this.BindForm.detailAddress
        })
        loadingInstance.close()
      }
    },
    changedAddress() {
      const vm = this
      if (vm.BindForm.address.province && vm.BindForm.address.city) {
        vm.province = vm.BindForm.address.province.code
        vm.city = vm.BindForm.address.city.code
        this.$refs.addRecoveryStore.getProvinceAndCity(vm.province, vm.city)
      }
      if (vm.BindForm.address.province) {
        vm.BindForm.provinceName = vm.BindForm.address.province.name
        vm.BindForm.cityName = ''
        vm.BindForm.villageName = ''
        vm.addressName()
      }
      if (vm.BindForm.address.city) {
        vm.BindForm.cityName = vm.BindForm.address.city.name
        vm.BindForm.villageName = ''
        vm.addressName()
      }
      if (vm.BindForm.address.village) {
        vm.BindForm.villageName = vm.BindForm.address.village.name
        vm.addressName()
      }
    },
    /** 返回上一页*/
    reback() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.go(-1)
    },
    /** 提交 */
    handelSubmit() {
      this.$refs.firstBindForm.validate(fv => {
        if (fv) {
          this.$refs.BindForm.validate(v => {
            if (v) {
              console.log(v)
              if (!this.BindForm.provinceCode) {
                this.$message.error('回收点所在省份不能为空')
                return
              }
              if (!this.BindForm.cityCode) {
                this.$message.error('回收点所在市不能为空')
                return
              }
              if (!this.BindForm.areaCode) {
                this.$message.error('回收点所在地区不能为空')
                return
              }
              if (!this.BindForm.detailAddress) {
                this.$message.error('回收点所在具体地址不能为空')
                return
              }
              if (this.center[0] == 120.19 && this.center[1] == 30.26) {
                this.$message.error('请重新选择回收点附近的坐标点')
                return
              }
              if (this.state == 'add') {
                const data = this.$XEUtils.clone(this.BindForm, true)
                data.provinceId = this.BindForm.provinceCode
                data.cityId = this.BindForm.cityCode
                data.areaId = this.BindForm.areaCode
                delete data.provinceCode
                delete data.cityCode
                delete data.areaCode
                if (data.cityName === data.provinceName) {
                  data.cityName = '市辖区'
                }
                console.log(data)
                const loadingInstance = Loading.service({ fullscreen: true })
                addRecovery(data)
                  .then(result => {
                    loadingInstance.close()
                    this.$store.dispatch('tagsView/delView', this.$route)
                    this.$message.success('添加成功')
                    this.$router.go(-1)
                  })
                  .catch(err => {
                    loadingInstance.close()
                    console.log(err)
                  })
              } else if (this.state === 'edit') {
                const data = this.$XEUtils.clone(this.BindForm, true)
                data['id'] = this.id
                data.provinceId = this.BindForm.provinceCode
                data.cityId = this.BindForm.cityCode
                data.areaId = this.BindForm.areaCode
                delete data.provinceCode
                delete data.cityCode
                delete data.areaCode
                if (data.cityName === data.provinceName) {
                  data.cityName = '市辖区'
                }
                console.log(data)
                const loadingInstance = Loading.service({ fullscreen: true })
                updateRecovery(data)
                  .then(result => {
                    loadingInstance.close()
                    this.$store.dispatch('tagsView/delView', this.$route)
                    this.$message.success('编辑成功')
                    this.$router.go(-1)
                  })
                  .catch(err => {
                    loadingInstance.close()
                    console.log(err)
                  })
              }
              /* this.$refs.BindForm[1].validate(validate => {
                if (validate) {

                }
              })*/
            }
          })
        }
      })
    },
    /** 区 */
    handelArea(v) {
      console.log(v, '区id')
      if (v) {
        this.BindForm.areaName = this.pca.area.find(inf => {
          return inf.code === v
        }).name
        this.BindForm.areaId = this.pca.area.find(inf => {
          return inf.code === v
        }).code
        this.addressName()
      }
    },
    /** 市 */
    handelCity(v) {
      if (v) {
        this.pca.forArea = []
        this.BindForm.areaName = ''
        this.BindForm.areaId = ''
        this.BindForm.areaCode = null
        const cityInfo = this.$XEUtils.find(this.pca.city, item => item.code === v)
        this.pca.area.forEach(inf => {
          if (inf.pid === cityInfo.id) {
            this.pca.forArea.push(inf)
          }
        })
        this.BindForm.cityName = this.pca.city.find(inf => {
          return inf.code === v
        }).name
        this.BindForm.cityId = this.pca.city.find(inf => {
          return inf.code === v
        }).code
      }
    },
    /** 省 */
    handelProvince(v) {
      this.pca.forCity = []
      this.pca.forArea = []
      this.BindForm.cityId = ''
      this.BindForm.areaId = ''
      this.BindForm.cityCode = null
      this.BindForm.areaCode = null
      if (v) {
        const provinceInfo = this.$XEUtils.find(this.pca.province, item => item.code === v)
        this.pca.city.forEach(inf => {
          if (inf.pid === provinceInfo.id) {
            this.pca.forCity.push(inf)
          }
        })

        this.BindForm.cityName = ''
        this.BindForm.areaName = ''
        this.BindForm.detailAddress = ''
        this.BindForm.provinceName = this.pca.province.find(inf => {
          return inf.code === v
        }).name
        this.BindForm.provinceId = this.pca.province.find(inf => {
          return inf.code === v
        }).id
        this.BindForm.provinceCode = this.pca.province.find(inf => {
          return inf.code === v
        }).code
        this.addressName()
      }
    },
    addressName() {
      this.BindForm.detailAddress = ''
      this.BindForm.detailAddress =
        this.BindForm.provinceName +
        this.BindForm.cityName +
        this.BindForm.areaName
    },
    /** 点击编辑上门公里数*/
    changeSupportDistance() {
      if (/^[0-9]*[1-9][0-9]*$/g.test(this.BindForm.supportDistance)) {
        if (this.BindForm.supportDistance < 0) {
          this.BindForm.supportDistance = 0
        } if (this.BindForm.supportDistance > 500) {
          this.BindForm.supportDistance = 500
        }
      } else {
        this.BindForm.supportDistance = null
      }
    },
    /** 修改时初始化 */
    provinceCity() {
      this.pca.forCiry = []
      this.pca.forArea = []
      this.pca.city.forEach(inf => {
        if (inf.pid === this.BindForm.provinceCode) {
          this.pca.forCiry.push(inf)
        }
      })
      this.pca.area.forEach(inf => {
        if (inf.pid === this.BindForm.cityCode) {
          this.pca.forArea.push(inf)
        }
      })
    },
    /** 初始地址 */
    loadCity() {
      getCityList()
        .then(result => {
          this.pca.province = []
          this.pca.city = []
          this.pca.area = []
          result.data.data.forEach(inf => {
            this.pca.province.push(inf.province)
            inf.cityRegion.forEach(reg => {
              this.pca.city.push(reg.city) // 拿市区
              reg.village.forEach(vil => {
                this.pca.area.push(vil) // 拿城区
              })
            })
          })
          this.inititalInfo()
        })
        .catch(err => {
          console.log(err)
        })
    },
    handelClose() {
      this.visible = false
    },
    handleCellStyle({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return 'background:#f3f3f3'
      } else {
        return ''
      }
    },
    /** 点击搜索后触发的事件 */
    onSearchResult(pois) {
      if (pois.length > 0) {
        pois.forEach(item => {
          if (this.$refs.searchBox.keyword == item.name) {
            this.center = [item.lng, item.lat]
          } else {
            // 这边类似模糊查询 会返回一个数组，我就直接取第一个值了。
            this.center = [pois[0].lng, pois[0].lat]
          }
        })
      }
      this.BindForm.detailAddress = this.$refs.searchBox.keyword
      this.BindForm.lat = this.center[1]
      this.BindForm.lng = this.center[0]
    }
  }
}
</script>

<style lang="scss" scoped>
.addRecovery {
  min-width: 1710px;
  padding: 50px 100px;
  .cus-hearder {
    font-size: 0.9rem;
    height: 50px;
    border-radius: 5px;
    line-height: 50px;
    padding: 0px 20px;
    background: #f3f3f3;
  }
  .sub-form {
    .hospitalInfo {
      width: 100%;
      border: 1px solid #ECECEC;
      border-radius: 5px;
      margin-bottom: 22px;
      .el-form-item .el-form-item {
        margin-bottom: 22px;
      }
    }
    ::v-deep.el-form {
      margin-top: 40px;
      .el-form-item__label {
        width: 140px;
        text-align: start;
      }
      .supportDistance {
        .el-form-item__error {
          margin-left: 218px;
        }
      }
      /*.el-form-item__error {
        margin-left: 140px;
      }*/
      .el-form-item {
        padding-left: 20px;
        .el-input {
          width: 200px;
        }
        .ele-table {
          width: 800px;
          .cus-column-commodity {
            display: flex;
            align-items: flex-start;

            .left {
              width: 60px;
              height: 60px;
            }
            .right {
              margin-left: 30px;
              display: flex;
              flex-direction: column;
              span:last-child {
                font-size: 0.7rem;
                color: gray;
              }
            }
          }
        }
        .el-card {
          width: 800px;
          .card-header {
            display: flex;
            align-items: center;
            .el-button {
              height: 28px;
            }
            .el-input {
              width: 100px;
              margin: 0px 10px;
            }
          }
        }
      }
      .urgent {
        .el-input {
          width: auto;
        }
      }
      .sub-footer {
        .el-button {
          margin-left: 140px;
          width: 100px;
          margin-top: 40px;
        }
      }
    }
    .time {
      ::v-deep .el-form-item__error {
        margin-left: 0 !important;
      }
    }
  }
}
</style>
